//
//  NSObject+MSObject.m
//  PeopleForTheFirstMall
//
//  Created by iOS on 2020/7/2.
//  Copyright © 2020 MS. All rights reserved.
//

#import "NSObject+MSObject.h"

@implementation NSObject (MSObject)

/** 转化为JSON data */
- (NSData *)ms_JSONData
{
    if ([self isKindOfClass:[NSString class]])
    {
        return [((NSString *)self) dataUsingEncoding:NSUTF8StringEncoding];
    }
    else if ([self isKindOfClass:[NSData class]])
    {
        return (NSData *)self;
    }
    
    return [NSJSONSerialization dataWithJSONObject:[self ms_JSONObject]
                                           options:kNilOptions
                                             error:nil];
}
/** 转化为数组或字典 */
- (id)ms_JSONObject
{
    if ([self isKindOfClass:[NSString class]])
    {
        return [NSJSONSerialization JSONObjectWithData:[((NSString *)self) dataUsingEncoding:NSUTF8StringEncoding]
                                               options:kNilOptions
                                                 error:nil];
    }
    else if ([self isKindOfClass:[NSData class]])
    {
        return [NSJSONSerialization JSONObjectWithData:(NSData *)self
                                               options:kNilOptions
                                                 error:nil];
    }
    
    return self;
}
/** 转化为JSON字符串，如需去收尾空格和换行调用 removeleadingAndTrailingSpaces */
- (NSString *)ms_JSONString
{
    if ([self isKindOfClass:[NSString class]])
    {
        return (NSString *)self;
    }
    else if ([self isKindOfClass:[NSData class]])
    {
        return [[NSString alloc] initWithData:(NSData *)self
                                     encoding:NSUTF8StringEncoding];
    }
    
    return [[NSString alloc] initWithData:[self ms_JSONData]
                                 encoding:NSUTF8StringEncoding];
}
/** 转化为JSON字符串并去掉 \ */
- (NSString *)ms_JSONString_Filter
{
    NSString *string = [self ms_JSONString];
    
    NSScanner *scanner = [NSScanner scannerWithString:string];
    NSString *text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<"intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">"intoString:&text];
        //替换字符
        string = [string stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text]withString:@""];
    }
//    NSString *regEx = @"<([^>]*)>";
//    html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    return string;
}

@end
